<script>
import debounce from "lodash/debounce";

export default {
  props: {
    api: Function,
    keywordName: {
      type: String,
      default: "name",
    },
    option: {
      type: Object,
    },
    popperClass: {
      type: String,
      default: "select-scroll",
    },
    multiple: {
      type: Boolean,
      default: false,
    },
    value: {
      type: [Number, Array, String],
      default: () => "",
    },
  },
  data() {
    return {
      searchParams: {
        pageNum: 1,
        pageSize: 30,
        keyword: "",
      },
      loading: false,
      hasMore: true,
      list: [],
    };
  },
  computed: {
    modelValue: {
      get() {
        return this.value;
      },
      set(val) {
        console.log(val);
        this.$emit("input", val);
      },
    },
  },
  mounted() {
    this.getList();
  },
  methods: {
    debouncedSearch: debounce(function (keyword) {
      this.handleSearch(keyword);
    }, 300),
    handleSearch(keyword) {
      this.searchParams.keyword = keyword;
      this.searchParams.pageNum = 1; // 重置页数
      this.list = []; // 清空当前列表
      this.hasMore = true; // 重置是否有更多数据
      this.getList();
    },
    handleFocus(e) {
      if (
        e.target.value !== this.searchParams.keyword &&
        e.target.value === ""
      ) {
        this.debouncedSearch(e.target.value);
      }
    },
    getList() {
      if (this.loading || !this.hasMore) return;
      this.loading = true;
      this.api({
        [this.keywordName]: this.searchParams.keyword,
        pageSize: this.searchParams.pageSize,
        pageNum: this.searchParams.pageNum,
      })
        .then((res = {}) => {
          const list = res.data.list;

          this.list.push(
            ...list.map((item) => {
              return {
                label: item[this.option.label],
                value: item[this.option.value],
              };
            }),
          );
          this.searchParams.pageNum++;
          if (list.length < this.searchParams.pageSize) {
            this.hasMore = false; // 若数据不足，标记为无更多数据
          }
          this.loading = false;
        })
        .catch(() => {
          this.loading = false;
        });
    },
    handleVisibleChange(visible) {
      const dom = document.querySelector(
        `.${this.popperClass} .el-scrollbar__wrap`,
      );
      if (!visible) {
        this.$nextTick(() => {
          dom.removeEventListener("scroll", this.handleScroll);
        });
      } else {
        this.$nextTick(() => {
          dom.addEventListener("scroll", this.handleScroll);
        });
      }
    },
    handleScroll(event) {
      const { scrollTop, clientHeight, scrollHeight } = event.target;
      if (
        scrollTop + clientHeight >= scrollHeight - 40 &&
        this.hasMore &&
        !this.loading
      ) {
        this.getList();
      }
    },
    // handleValueChange(newVal) {
    //   this.$emit("change", newVal);
    // },
  },
};
</script>

<template>
  <el-select
    v-model="modelValue"
    style="width: 400px"
    filterable
    remote
    clearable
    placeholder="请输入关键词"
    :multiple="multiple"
    :remote-method="debouncedSearch"
    :popper-class="popperClass"
    @visible-change="handleVisibleChange"
    @focus="handleFocus"
  >
    <!--@change="handleValueChange"-->
    <el-option
      v-for="item in list"
      :key="item.value"
      :label="item.label"
      :value="item.value"
    >
    </el-option>
  </el-select>
</template>

<style scoped></style>
